package controllers

import java.awt.image.BufferedImage
import java.awt.{Color, Font}
import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.Date
import javax.imageio.ImageIO

import DB.Admin
import common.{NeedLoginExcepiton, TimeTool}
import common.Tool._
import org.apache.commons.codec.binary.Base64
import play.api.libs.iteratee.Enumerator
import play.api.mvc._

import scala.collection.mutable.{Map => mutableMap}
import scala.concurrent.{Await, Future}
import scala.io.Source
import scala.util.Random

/**
 * Created by 林 on 14-4-10.
 */
object UtilController extends BaseController {

  def uploadWithUrl = JsAction(parse.multipartFormData) { request =>
    val fileName=request.getQueryString("fileName")
      val key = if(fileName.isEmpty) "uploads/"+ System.currentTimeMillis().toString else fileName.get
      Future {
        fs.saveFile(key, tempFileToArray(request.body.files.head.ref))
      }
      val url=fs.getFileUrl(key)
    Ok(Map("code" -> 200, "msg" -> "成功", "url" -> url).toJson)
  }
  //文件上传
  def uploadBodyWithUrl = JsAction(parse.raw(1024*1024*8)){ request =>
    val key = setting("imgPath") +System.currentTimeMillis().toString
    val data=request.body.asBytes(1024*1024*8).getOrElse(Array[Byte](0))
    println(data.length)
    fs.saveFile(key,data)
    val url=fs.getFileUrl(key)
    Ok(Map("code" -> 200, "msg" -> "成功", "url" -> url).toJson)
  }

  def download(name: String) = JsAction {
    val v = fs.getFile(name)
    if (v.isDefined) {
      Result(
        ResponseHeader(200, Map("Content-Type" -> "application/octet-stream", "Content-Length" -> v.get.length)),
        Enumerator.fromStream(fs.Byte2Stream(v.get))
      )
    } else {
      NotFound
    }
  }

  def getUrl(keys: String) = JsAction {
    val lists = keys.split(",").map(name => fs.getFileUrl(name))
    Ok(Map("code" -> 200, "msg" -> "成功", "bean" -> lists).toJson)
  }

  //图片验证码
  def pic = JsAction {
    implicit request =>
      val img = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB)
      //图片绘图对象
      val g = img.getGraphics()
      val c = new Color(250, 250, 250)
      g.setColor(c)
      // 填充整个图片的颜色
      g.fillRect(0, 0, 68, 22)
      // 输出数字和字母
      val sb = new StringBuffer()
      val ch = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789".toCharArray()
      0 to 3 foreach {
        i =>
          val index = Random.nextInt(ch.length)
          g.setColor(new Color(Random.nextInt(88), Random.nextInt(188), Random.nextInt(255)))
          g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22)) // 字体和大小
          g.drawString("" + ch(index), (i * 15) + 3, 18)
          sb.append(ch(index))
      }
      val out = new ByteArrayOutputStream()
      ImageIO.write(img, "JPG", out)
      val imgContent = Enumerator.fromStream(new ByteArrayInputStream(out.toByteArray))
      Result(
        header = ResponseHeader(200),
        body = imgContent
      ).withSession(request.session + ("picCode" -> sb.toString.encrypt()))
  }

  def systemInfo=Action.async {
    Future {
      Ok(setting.toJson)
    }
  }

  /**
    * 静态文件处理
 *
    * @param pack
    * @param file
    * @return
    */
  def staticFile(pack: String, file: String) = Action {
    implicit request =>
      try {
        val clazz = Class.forName(s"views.html.$pack.$file")
        val method =
          try {
            clazz.getMethod("apply", classOf[Map[String, String]])
          } catch {
            case e: NoSuchMethodException =>
              try {
                clazz.getMethod("apply", classOf[Admin], classOf[Map[String, String]])
              }catch{
                case a:NoSuchMethodException=>
                  clazz.getMethod("apply")
              }
          }
        Ok(if (method.getParameterTypes.length > 1) {
          val sessionUid = request.session.get("uid")
          if (sessionUid.isEmpty) throw new NeedLoginExcepiton
          val uid = sessionUid.get
          val u = cacheMethod("admin_cache_data_" + uid, 10) {new Admin().queryById(uid).dbCheck}
          method.invoke(clazz, u, setting).asInstanceOf[play.twirl.api.HtmlFormat.Appendable]
        } else if(method.getParameterTypes.length == 1){
          method.invoke(clazz, setting).asInstanceOf[play.twirl.api.HtmlFormat.Appendable]
        }else{
          method.invoke(clazz).asInstanceOf[play.twirl.api.HtmlFormat.Appendable]
        })
      } catch {
        case e: ClassNotFoundException => Status(404)
        case l: NeedLoginExcepiton => Redirect("/back/login")
      }
  }


}
